package com.yuandian.management.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuandian.api.business_monitor.po.SearchParams;
import com.yuandian.api.management.entity.ConfEmployee;
import com.yuandian.bpm.common.core.util.R;
import com.yuandian.bpm.common.security.util.SecurityUtils;
import com.yuandian.management.dto.BaseConfDTO;
import com.yuandian.management.mapper.ConfEmployeeMapper;
import com.yuandian.management.service.ConfEmployeeService;
import com.yuandian.management.vo.EmployeeVo;
import com.yuandian.utils.poi.BatchDataResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 营业员配置表-Service实现
 * @author zfsn
 * @date 2023-3-28
 */
@Service
public class ConfEmployeeServiceImpl extends ServiceImpl<ConfEmployeeMapper, ConfEmployee>
		implements ConfEmployeeService {

	@Autowired
	private ConfEmployeeMapper confEmployeeMapper;

	/**
	 * 新增数据
	 *
	 * @param confEmployee 实例对象
	 * @return 通用返回对象
	 */
	@Override
	public R<String> saveEmployee(ConfEmployee confEmployee) {
		if (!checkEmployeeDuplicates(confEmployee)) {
			//todo 未清楚token 没能解析出用户名
//			confEmployee.setCreateBy(SecurityUtils.getUser().getName());
			super.save(confEmployee);
			return R.ok();
		}
		return R.failed("操作员已存在");
	}

	/**
	 * 通过主键更新数据
	 *
	 * @param confEmployee 实例对象
	 * @return 通用返回对象
	 */
	@Override
	public R<String> updateEmployeeById(ConfEmployee confEmployee) {
		if (!checkEmployeeDuplicates(confEmployee)) {
			confEmployee.setUpdateBy(SecurityUtils.getUser().getName());
			confEmployee.setUpdateTime(LocalDateTime.now());
			super.updateById(confEmployee);
			return R.ok();
		}
		return R.failed("操作员已存在");
	}


	/**
	 * 判断操作员是否重复
	 * @param confEmployee
	 * @return
	 */
	private boolean checkEmployeeDuplicates(ConfEmployee confEmployee){
		QueryWrapper<ConfEmployee> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("num",confEmployee.getNum());
		queryWrapper.eq("business_hall_num",confEmployee.getBusinessHallNum());
		if (confEmployee.getId() != null){
			queryWrapper.ne("id", confEmployee.getId());
		}
		return super.count(queryWrapper) > 0;
	}



	/**
	 * 分页查询
	 *
	 * @param confEmployee 筛选条件
	 * @return 通用返回对象
	 */
	@Override
	public Page<ConfEmployee> listPage(ConfEmployee confEmployee) {
		return confEmployeeMapper.listPage(new Page<>(confEmployee.getPageNum(), confEmployee.getPageSize()), confEmployee);
	}

	@Override
	public Map<String, String> getOperatorMap(SearchParams params) {
		Map<String, String> resultMap = new HashMap<>();
		if (Objects.isNull(params)) {
			params = new SearchParams();
		}

		List<BaseConfDTO> operators = confEmployeeMapper.getOperators(params);
		if (!CollectionUtils.isEmpty(operators)) {
			resultMap = operators.stream().collect(Collectors.toMap(BaseConfDTO::getOperatorId, BaseConfDTO::getLabel));
		}

		return resultMap;
	}

	/**
	 * 根据操作员列表获取操作员Id列表
	 *
	 * @param operatorName
	 * @return 搜索选项vo对象集合
	 */
	@Override
	public List<String> getOperatorIdListByOperatorNameList(String operatorName) {
		SearchParams params = new SearchParams();
		params.setOperatorName(operatorName);

		List<String> businessHallIdList = new ArrayList<>();
		// 根据单位名称获取单位编号
		List<BaseConfDTO> operators = confEmployeeMapper.getOperators(params);
		if (!CollectionUtils.isEmpty(operators)) {
			businessHallIdList = operators.stream().map(BaseConfDTO::getOperatorId).distinct().collect(Collectors.toList());
		}

		return businessHallIdList;
	}

	/**
	 * 保存导入的数据
	 *
	 * @param dataList
	 */
	@Override
	public void saveBatchExcelData(List<EmployeeVo> dataList) {
		if(!CollectionUtils.isEmpty(dataList)) {
			Set<ConfEmployee> insertSet = new HashSet<>();
			for (EmployeeVo employeeVo : dataList) {
				ConfEmployee confEmployee = new ConfEmployee();
				confEmployee.setName(employeeVo.getName());
				confEmployee.setNum(employeeVo.getNum());
				confEmployee.setBusinessHallNum(employeeVo.getBusinessHallNum());
				insertSet.add(confEmployee);
			}
			super.saveBatch(insertSet);
		}
	}

	/**
	 * 入库前-批量校验数据
	 *
	 * @param dataList
	 * @return
	 */
	@Override
	public BatchDataResult<EmployeeVo> checkBatchExcelData(List<EmployeeVo> dataList) {
		List<EmployeeVo> successList = new ArrayList<>();
		List<EmployeeVo> failList = new ArrayList<>();

		Set<String> existNumSet = confEmployeeMapper.listEmployNumAndBusinessHallNum();
		for (EmployeeVo employeeVo : dataList) {
			String key = employeeVo.getNum().trim() + employeeVo.getBusinessHallNum().trim();
			if (!existNumSet.contains(key)) {
				successList.add(employeeVo);
			}else {
				failList.add(employeeVo);
			}
		}

		return new BatchDataResult<>(true, successList,failList);
	}

	/**
	 * 解析阶段-校验数据
	 *
	 * @param data
	 * @return
	 */
	@Override
	public boolean checkExcelData(EmployeeVo data) {
		try {
			Field[] fields = data.getClass().getDeclaredFields();
			for (Field field : fields) {
				field.setAccessible(true);
				if (Objects.isNull(field.get(data))) {
					return false;
				}
			}
		} catch (IllegalAccessException e) {
			log.error(e.getMessage(), e);
			return false;
		}
		return true;
	}
}
